<?php
/**
 * 
 * 
 * @author walkor <workerman.net>
 * 
 */

require_once ROOT_DIR . '/Protocols/JsonProtocol.php';
require_once ROOT_DIR."/Lib/cls_mysql.php";
class Event
{
    public static $cls_mysql=null;
    public static $robot_ids = array(100,101,102,103,104,105,106,107,108,109);
    /**
     * 网关有消息时，判断消息是否完整
     */
    public static function onGatewayMessage($buffer)
    {
        return JsonProtocol::check($buffer);
    }
    
    public static  function get_mysql(){
        if(!Event::$cls_mysql){
            Event::$cls_mysql = new cls_mysql("127.0.0.1", "root", "zhy611611", "smeoa", "utf8");
        }
        return Event::$cls_mysql;
    }

    /**
    * 此链接的用户没调用GateWay::notifyConnectionSuccess($uid);前（即没有得到验证），都触发onConnect
    * 已经调用GateWay::notifyConnectionSuccess($uid);的用户有消息时，则触发onMessage
    * @param string $message 一般是传递的账号密码等信息
    * @return void
    */
   public static function onConnect($message)
   {
       /*
        * 通过message验证用户，并获得uid。
        * 一般流程这里$message应该包含用户名 密码，然后根据用户名密码从数据库中获取uid
        * 这里只是根据时间戳生成uid，高并发下会有小概率uid冲突
        */ 
       //$uid = self::checkUser($message);
       $connect_arr = JsonProtocol::decode($message);
       $action = $connect_arr["action"];
       $uid = $connect_arr["uid"];
       // 不合法踢掉
       if(!$uid)
       {
           // 踢掉
           return GateWay::kickCurrentUser();
       }
       
       Event::kickUser($uid);
       
       // [这步是必须的]合法，记录uid到gateway通信地址的映射
       GateWay::storeUid($uid);
       
       // [这步是必须的]发送数据包到address对应的gateway，确认connection成功
       GateWay::notifyConnectionSuccess($uid);
       
       // 向当前用户发送uid
       GateWay::sendToCurrentUid(JsonProtocol::encode(array("action"=>"connect","uid"=>$uid,"succ"=>1)));
       
       // 广播所有用户，xxx connected
       //GateWay::sendToAll(JsonProtocol::encode(array("action"=>"notify",'from_uid'=>'SYSTEM',"come_uid"=>$uid, 'message'=>"$uid come \n", 'to_uid'=>'all')));
   }
   
   
   
   /**
    * 有消息时触发该方法
    * @param int $uid 发消息的uid
    * @param string $message 消息
    * @return void
    */
   public static function onMessage($uid, $message)
   {
        $message_data = JsonProtocol::decode($message);
        $mysql = Event::get_mysql();
        $action = $message_data["action"];
        switch ($action){
            case "message":
              // 向所有人发送
               if($message_data['to_uid'] == 'all')
                 {
                    return GateWay::sendToAll($message);
                  }
                // 向某个人发送
                 else
                 {
                    return GateWay::sendToUid($message_data['to_uid'], $message);
                 }
                break;
            case "get_all_desks":
                $desks = Event::get_all_desks($message_data);
                $response = array("action"=>$action,"lists"=>$desks);
                return GateWay::sendToCurrentUid(JsonProtocol::encode($response));
                break;
            case "game_desk_search":
                $desks = Event::get_search_desk($message_data);
                $response = array("action"=>@"get_all_desks","lists"=>$desks);
                return GateWay::sendToCurrentUid(JsonProtocol::encode($response));
                break;
            case "add_desk":
                $succ = Event::add_to_desk($uid,$message_data);
                if(!$succ[0]){ //vip 加入进来
                    $result = $succ[6];
                    $response = array();
                    if($result["password"]){
                        $response["need_password"] = 1;
                        $response["password"] = $result["password"];
                    }else{
                        $response["need_password"] = 0;
                    }
                    $response["action"] = "game_add_vip_desk";
                    $response["succ"] = 1;
                    $response["left_user_id"] = $result["left_user_id"];
                    $response["right_user_id"] = $result["right_user_id"];
                    $response["left_rand_str"] = $result["left_rand_str"];
                    $response["right_rand_str"] = $result["right_rand_str"];
                    $response["left_last_call"] = $result["left_last_call"];
                    $response["right_last_call"] = $result["right_last_call"];
                    $response["game_id"] = $result["game_id"];
                    $response["desk_id"] = $result["desk_id"];
                    $response["section_id"] = $result["section_id"];
                    
                   // $response = array("left_user_id"=>$result["left_user_id"],"is_new"=>$succ[3],"game_id"=>$message_data["game_id"],"desk_id"=>$succ[2],"section_id"=>$message_data["section_id"]);
                }else{
                    $response = array("action"=>$action,"need_password"=>$succ[4],"password"=>$succ[5],"gold"=>$succ[6],"succ"=>1,"seat"=>$succ[0],"other_user_id"=>$succ[1],"is_new"=>$succ[3],"game_id"=>$message_data["game_id"],"desk_id"=>$succ[2],"section_id"=>$message_data["section_id"]);
                }
                GateWay::sendToCurrentUid(JsonProtocol::encode($response));
                
                //给所有在线用户发送通知，刷新各自的游戏大厅
                $desks = Event::get_all_desks($message_data);
                $response = array("action"=>"get_all_desks","lists"=>$desks);
                GateWay::sendToAll(JsonProtocol::encode($response));
                break;
            //有密码的桌子，对方输入密码成功
            case "game_passowrd_succ":
                $section_id = $message_data["section_id"];
                $game_id = $message_data["game_id"];
                $desk_id = $message_data["desk_id"];
                $seat = $message_data["seat"];
                $vip = $message_data["vip"];
                if($vip){
                    GateWay::sendToCurrentUid(JsonProtocol::encode(array("action"=>$action,"succ"=>$succ)));
                    break;
                }
                $other_user_id = Event::get_other_user_id($game_id, $section_id, $desk_id, $seat);
                $response = array("action"=>"add_desk_other","come_uid"=>$uid,"game_id"=>$game_id,"desk_id"=>$desk_id,"section_id"=>$section_id);
                GateWay::sendToUid($other_user_id, JsonProtocol::encode($response));
                $sql = "update game_room set right_user_id = $uid, is_all = 1 where game_id = $game_id and section_id = $section_id and desk_id = $desk_id";
                $succ = $mysql->query($sql);
                GateWay::sendToCurrentUid(JsonProtocol::encode(array("action"=>$action,"succ"=>$succ)));
                break;
            case "game_set_desk_pass":
                $succ = Event::set_desk_password($uid, $message_data);
                if(!$succ[0]){
                    $response = array("action"=>$action,"succ"=>0);
                }else{
                    $response = array("action"=>$action,"succ"=>1);
                }
                GateWay::sendToCurrentUid(JsonProtocol::encode($response));
                break;
            case "game_set_gold":
                $section_id = $message_data["section_id"];
                $game_id = $message_data["game_id"];
                $desk_id = $message_data["desk_id"];
                $seat = $message_data["seat"];
                $succ = Event::set_game_gold($uid,$message_data);
                $gold = $message_data["gold"];
                $response = array("action"=>"game_set_gold_suc","gold"=>$gold,"succ"=>1);
                GateWay::sendToCurrentUid(JsonProtocol::encode($response));
                
                $other_user_id = Event::get_other_user_id($game_id, $section_id, $desk_id,$seat);
                GateWay::sendToUid($other_user_id, JsonProtocol::encode($response));
                
                 //广播所有用户，有人已经不在某个桌子
                $desks = Event::get_all_desks($message_data);
                $response = array("action"=>"get_all_desks","lists"=>$desks);
                GateWay::sendToAll(JsonProtocol::encode($response));
                
               
                return;
                break;
            case "game_start":
                $section_id = $message_data["section_id"];
                $game_id = $message_data["game_id"];
                $desk_id = $message_data["desk_id"];
                $seat = $message_data["seat"];
                $gold = isset($message_data["gold"])?$message_data["gold"]:0;
                //左边的那人的5个骰子(1-6)
                $result_str = Event::get_random();
                
                Event::save_rand($game_id, $section_id, $desk_id, $seat, $uid, $result_str,$gold);
                 
                $call_first = Event::get_call_first($game_id, $section_id, $desk_id);
                
                $check_all_start = Event::checkAllStart($game_id, $section_id, $desk_id);
                
                if($seat == $call_first){
                    $call = 1;
                }else{
                    $call = 0;
                }
                
                //通知另外一个人，是否全部开始了
                $other_user_id = Event::get_other_user_id($game_id, $section_id, $desk_id,$seat);
                //机器人
                if(array_search($other_user_id, Event::$robot_ids)===FALSE){
                    GateWay::sendToUid($other_user_id, JsonProtocol::encode(array("action"=>"all_start","gold"=>$gold,"all_start"=>$check_all_start)));
                
                    GateWay::sendToCurrentUid(JsonProtocol::encode(array("action"=>$action, "data_str"=>$result_str,"call"=>$call,"gold"=>$gold,"all_start"=>$check_all_start)));
                }else{
                    $check_all_start = 1;
                   // sleep(3000);
                   // for($i=0;$i<15000000;$i++){
                     //       ;
                    //}
                    GateWay::sendToCurrentUid(JsonProtocol::encode(array("action"=>$action, "data_str"=>$result_str,"call"=>$call,"gold"=>$gold,"all_start"=>$check_all_start)));
       
                    $result_str2 = Event::get_random();
                
                    Event::save_rand($game_id, $section_id, $desk_id, 1, $other_user_id, $result_str2,$gold);
                    
                    if($call ==0){
                        $first = rand(2, 3);
                        $second = rand(2,5);
                        $call2 = "$first,$second";
                        for($i=0;$i<65000000;$i++){
                            ;
                        }
                        Event::save_call($game_id, $section_id, $desk_id, 1, $other_user_id, $call2);
                        $response2= array("action"=>"game_other_call", "call"=>$call2);
                        GateWay::sendToCurrentUid(JsonProtocol::encode($response2));
                    }            
                   }
                
                return ;
                
                break;
           
            case "game_call":
                $section_id = $message_data["section_id"];
                $game_id = $message_data["game_id"];
                $desk_id = $message_data["desk_id"];
                $seat = $message_data["seat"];
                $call = $message_data["call"];//某个人叫骰子，要通知另外一个人
                //数据库中保存
                
                Event::save_call($game_id, $section_id, $desk_id, $seat, $uid, $call);
                
                $other_user_id = Event::get_other_user_id($game_id, $section_id, $desk_id,$seat);
                if($other_user_id){
                    $response= array("action"=>"game_other_call", "call"=>$call);
                    if(array_search($other_user_id, Event::$robot_ids)!==FALSE){
                        $call_arr = explode(",", $call);
                        $first = $call_arr[0];
                        $second = $call_arr[1];
                        $is_end = rand(1, 8);
                        
                        //sleep(30000);
                        for($i=0;$i<60000000;$i++){
                            ;
                        }
                        if(($first == 10 && $second == 1) ||($is_end == 3)){
                           for($i=0;$i<10000000;$i++){
                                ;
                            }
                            Event::game_end($section_id, $game_id, $desk_id, 1, $call, 0,$other_user_id);
                            return;
                        }else{
                            $f_max = min($first + 3,10);
                            if($second == 1){
                                $first2 = rand($first+1, $f_max);
                                $second2 = rand(1,6);
                            }else{
                                $first2 = rand($first,$f_max);
                                if($second ==6){
                                    if($first2 == $first){
                                        $second2 = 1;
                                    }else{
                                        $second2 = rand(1,6);
                                    }
                                }else{
                                    $second2 = rand($second+1,6);
                                }
                                
                            }
                            $response = array("action"=>"game_other_call", "call"=>$first2.",".$second2);
                        }
                        
                         Event::save_call($game_id, $section_id, $desk_id, 1, $other_user_id, $first2.",".$second2);
                         
                        return GateWay::sendToCurrentUid(JsonProtocol::encode($response));
                    }else{
                        return GateWay::sendToUid($other_user_id, JsonProtocol::encode($response));
                    }
                }
                break;
            case "game_use_tools":
                $tid = $message_data["tid"];
                $section_id = $message_data["section_id"];
                $game_id = $message_data["game_id"];
                $desk_id = $message_data["desk_id"];
                $seat = $message_data["seat"];
                $succ = Event::use_tools($uid,$tid);
                $other_user_id = Event::get_other_user_id($game_id, $section_id, $desk_id, $seat);
                $response= array("action"=>"game_other_use_tools", "tid"=>$tid);
                return  GateWay::sendToUid($other_user_id, JsonProtocol::encode($response));
                break;
            case "game_end":
                $section_id = $message_data["section_id"];
                $game_id = $message_data["game_id"];
                $desk_id = $message_data["desk_id"];
                $seat = $message_data["seat"];
                $call = $message_data["call"];//某个人叫开骰，那么这个记录是另外一个人上次的记录
                $gold = $message_data["gold"];
                Event::game_end($section_id,$game_id,$desk_id,$seat,$call,$gold,$uid);
                return;
                break;
            case "game_exit"://正常或者中途退出游戏
                $section_id = $message_data["section_id"];
                $game_id = $message_data["game_id"];
                $desk_id = $message_data["desk_id"];
                $seat = $message_data["seat"];
                $is_complete = $message_data["is_complete"];
                $response= array("action"=>$action);
               
                //通知对方玩家，对手退出或者逃跑
                $other_user_id = Event::get_other_user_id($game_id, $section_id, $desk_id,$seat);
                GateWay::sendToUid($other_user_id, JsonProtocol::encode(array("action"=>"other_user_exit","is_complete"=>$is_complete)));
                
                //通知VIP观战者，有人已经退出该桌子,观战者强制退出观战模式
                $sql = "select * from game_room where game_id = '$game_id' and section_id = '$section_id' and desk_id = '$desk_id'";
                $result = $mysql->getRow($sql);
                
                 if(!$is_complete){
                    Event::addUserGold($uid,(-1)*$result["gold"]);
                }
                
                if($result["vipers"]){
                    $vipers = explode(",", $result["vipers"]);
                    if(is_array($vipers)){
                        foreach($vipers as $key=>$val){
                            $response= array("action"=>"game_vip_user_exit", "user_id"=>$uid);
                            GateWay::sendToUid($val, JsonProtocol::encode($response));
                        }
                    }else{
                        $response= array("action"=>"game_vip_user_exit", "user_id"=>$uid);
                        GateWay::sendToUid($vipers, JsonProtocol::encode($response));
                    }
                }
               
                Event::kickUser($uid);
                GateWay::sendToCurrentUid(JsonProtocol::encode($response));
                
                //广播所有用户，有人已经不在某个桌子
                $desks = Event::get_all_desks($message_data);
                $response = array("action"=>"get_all_desks","lists"=>$desks);
                GateWay::sendToAll(JsonProtocol::encode($response));
                
                break;
            case "game_add_gold"://某个玩家加注
                $section_id = $message_data["section_id"];
                $game_id = $message_data["game_id"];
                $desk_id = $message_data["desk_id"];
                $seat = $message_data["seat"];
                $add_gold = intval($message_data["add_gold"]);
                $other_user_id = Event::get_other_user_id($game_id, $section_id, $desk_id, $seat);
                if($other_user_id){
                    GateWay::sendToUid($other_user_id, JsonProtocol::encode(array("action"=>"other_add_gold","add_gold"=>$add_gold)));
                }else{
                    $sql ="update game_room set gold = gold + $add_gold where  game_id = '$game_id' and section_id = '$section_id' and desk_id = '$desk_id'";
                    $mysql->query($sql);
                    GateWay::sendToCurrentUid(JsonProtocol::encode(array("action"=>"game_add_gold_suc","succ"=>1,"add_gold"=>$add_gold)));
                }
                break;
            
            case "game_add_gold_suc"://另外一个玩家确认加注
                $section_id = $message_data["section_id"];
                $game_id = $message_data["game_id"];
                $desk_id = $message_data["desk_id"];
                $seat = $message_data["seat"];
                $add_gold = isset($message_data["add_gold"])?$message_data["add_gold"]:0;
                $succ = isset($message_data["succ"])?$message_data["succ"]:0;
                if($succ >0){
                    $sql ="update game_room set gold = gold + $add_gold where  game_id = '$game_id' and section_id = '$section_id' and desk_id = '$desk_id'";
                    $mysql->query($sql);
                }
                $other_user_id = Event::get_other_user_id($game_id, $section_id, $desk_id, $seat);
                GateWay::sendToUid($other_user_id, JsonProtocol::encode(array("action"=>"game_add_gold_suc","succ"=>$succ,"add_gold"=>$add_gold)));
                break;
            case "game_call_gold"://索取金币
                $section_id = $message_data["section_id"];
                $game_id = $message_data["game_id"];
                $desk_id = $message_data["desk_id"];
                $seat = $message_data["seat"];
                $other_user_id = Event::get_other_user_id($game_id, $section_id, $desk_id, $seat);
                GateWay::sendToUid($other_user_id, JsonProtocol::encode(array("action"=>"other_call_gold")));
                break;
            case "game_given_gold"://赠送金币给对方
                $section_id = $message_data["section_id"];
                $game_id = $message_data["game_id"];
                $desk_id = $message_data["desk_id"];
                $seat = $message_data["seat"];
                $given_gold = $message_data["given_gold"];
                $other_user_id = Event::get_other_user_id($game_id, $section_id, $desk_id, $seat);
                $resss = Event::addUserGold($uid, -1*$given_gold);
                if($resss){
                    Event::addUserGold($other_user_id, $given_gold);
                    GateWay::sendToUid($other_user_id, JsonProtocol::encode(array("action"=>"game_other_given","given_gold"=>$given_gold)));
                    GateWay::sendToCurrentUid( JsonProtocol::encode(array("action"=>"game_given_gold_succ","succ"=>1)));
                }else{
                    GateWay::sendToCurrentUid( JsonProtocol::encode(array("action"=>"game_given_gold_succ","succ"=>0)));
                }
            case "game_vip_exit"://VIP退出观战
                $section_id = $message_data["section_id"];
                $game_id = $message_data["game_id"];
                $desk_id = $message_data["desk_id"];
                $sql = "select * from game_room where game_id = '$game_id' and section_id = '$section_id' and desk_id = '$desk_id'";
                $result = $mysql->getRow($sql);
                if($result["vipers"]){
                 $vipers = explode(",", $result["vipers"]);
                 if(is_array($vipers)){
                     $vip_arr = array();
                     foreach($vipers as $key=>$val){
                          if($uid == $val){
                              continue;
                          }
                          $vip_arr []=$val;
                     }
                     $vip_str = implode(",", $vip_arr);
                 }else{
                    $vip_str = "";
                 }
                 $sql = "update game_room set vipers = '$vip_str' where game_id = '$game_id' and section_id = '$section_id' and desk_id = '$desk_id'";
                 $mysql->query($sql);
                }
                $response= array("action"=>$action);
                GateWay::sendToCurrentUid(JsonProtocol::encode($response));
                break;
        }
       
   }
   public static function game_end($section_id,$game_id,$desk_id,$seat,$call,$gold,$uid){
       //判断输赢
                $mysql = Event::get_mysql();
                $vectory = Event::game_end_dec($game_id,$section_id,$desk_id,$seat,$uid,$call);
               
                //保存输赢
                $data = array("user_id"=>$uid,"game_id"=>$game_id,"section_id"=>$section_id,"desk_id"=>$desk_id,
                    "seat"=>$seat,"gold"=>$gold,"result"=>$vectory["vectory"], "add_time"=>date("Y-m-d H:i:s"));
                $mysql->autoExecute("think_game_log",$data);
                $other_user_id = Event::get_other_user_id($game_id, $section_id, $desk_id,$seat);
                 $call_first = 1;
                if($vectory["vectory"] == 1){
                   // Event::addUserGold($uid, $gold);
                    $real_gold = Event::gameOverCal($other_user_id, -1, $gold);
                    
                    $response= array("action"=>"game_over","real_gold"=>$real_gold, "vectory"=>$vectory["vectory"],"other_rand_str"=>$vectory["other_rand_str"]);
                   // GateWay::sendToCurrentUid(JsonProtocol::encode($response));
                     GateWay::sendToUid($uid, JsonProtocol::encode($response));
                    
                    Event::gameOverCal($uid, 1, $real_gold);
              
                    if($seat == 1){
                        $call_first = 2;
                    }else{
                        $call_first =1;
                    }
                   if($other_user_id){
                        $response= array("action"=>"game_over","real_gold"=>$real_gold, "vectory"=>1-$vectory["vectory"],"other_rand_str"=>$vectory["my_rand_str"]);
                         GateWay::sendToUid($other_user_id, JsonProtocol::encode($response));
                    }
                }else{
                    //Event::addUserGold($uid, -1 * $gold);
                    $real_gold = Event::gameOverCal($uid, -1, $gold);
                   if($other_user_id){
                        $response= array("action"=>"game_over","real_gold"=>$real_gold, "vectory"=>1-$vectory["vectory"],"other_rand_str"=>$vectory["my_rand_str"]);
                         GateWay::sendToUid($other_user_id, JsonProtocol::encode($response));
                    }
                    Event::gameOverCal($other_user_id, 1, $real_gold);
                    $call_first = $seat;
                    
                    $response= array("action"=>"game_over","real_gold"=>$real_gold, "vectory"=>$vectory["vectory"],"other_rand_str"=>$vectory["other_rand_str"]);
                     //GateWay::sendToCurrentUid(JsonProtocol::encode($response));
                     GateWay::sendToUid($uid, JsonProtocol::encode($response));
                }
             
                 //保存输赢
                $data = array("user_id"=>$other_user_id,"game_id"=>$game_id,"section_id"=>$section_id,"desk_id"=>$desk_id,
                    "seat"=>$seat,"gold"=>$gold,"result"=>1-$vectory["vectory"], "add_time"=>date("Y-m-d H:i:s"));
                $mysql->autoExecute("think_game_log",$data);
              
                
                $mysql->query("update game_room set call_first = $call_first where game_id = '$game_id' and section_id = '$section_id' and desk_id = '$desk_id'");
                
                $sql = "select * from game_room where game_id = '$game_id' and section_id = '$section_id' and desk_id = '$desk_id'";
                $result = $mysql->getRow($sql);
                if(($seat == 1 && $vectory["vectory"] == 1) || ($seat == 2 && $vectory["vectory"] == 0)){
                   if($result["vipers"]){
                    $vipers = explode(",", $result["vipers"]);
                    if(is_array($vipers)){
                        foreach($vipers as $key=>$val){
                              $response= array("action"=>"game_vip_over", "vectory"=>1);
                              GateWay::sendToUid($val, JsonProtocol::encode($response));
                        }
                    }else{
                        $response= array("action"=>"game_vip_over", "vectory"=>1);
                        GateWay::sendToUid($vipers, JsonProtocol::encode($response));
                    }
                   }
                }else{
                   if($result["vipers"]){
                    $vipers = explode(",", $result["vipers"]);
                    if(is_array($vipers)){
                        foreach($vipers as $key=>$val){
                              $response= array("action"=>"game_vip_over", "vectory"=>0);
                              GateWay::sendToUid($val, JsonProtocol::encode($response));
                        }
                    }else{
                        $response= array("action"=>"game_vip_over", "vectory"=>0);
                        GateWay::sendToUid($vipers, JsonProtocol::encode($response));
                    }
                   } 
                }
                Event::clear_str($game_id, $section_id, $desk_id);
   }
   public static function use_tools($uid, $tid){
            $mysql = Event::get_mysql();
            $sql = "select * from think_member_tools where uid = '$uid' and tid = '$tid'";
            $info = $mysql->getRow($sql);
            if($info){
                if($info["tools_num"] == 1){
                    $sql = "delete from think_member_tools where id = '{$info["id"]}'";
                    return $mysql->query($sql);
                }else{
                    $sql = "update think_member_tools set tools_num = tools_num -1 where id = '{$info["id"]}'";
                    return $mysql->query($sql);
                }
            }else{
                return 0;
            }
        }

      public static function set_game_gold($uid,$message){
       $game_id = $message["game_id"];
       $section_id = $message["section_id"];
       $desk_id = $message["desk_id"];
       $gold = $message["gold"];
       $mysql = Event::get_mysql();
       $sql = "update game_room set `gold` = '$gold' , `init_gold` = '$gold' where game_id = '$game_id' and section_id = '$section_id' and desk_id = '$desk_id'";
       $succ = $mysql->query($sql);
       return $succ;
   }

   //删除字符串
   public static function clear_str($game_id, $section_id, $desk_id)
   {
       $mysql = Event::get_mysql();
       $sql="update game_room set left_rand_str = '', right_rand_str = '',left_last_call = '', right_last_call = '' where game_id = '$game_id' and section_id = '$section_id' and desk_id = '$desk_id'";
       $mysql->query($sql);
   }
   
   //检查某个桌子是否全部准备好了
   public static function checkAllStart($game_id, $section_id, $desk_id)
   {
       $mysql = Event::get_mysql();
       $sql="select * from game_room where game_id = '$game_id' and section_id = '$section_id' and desk_id = '$desk_id'";
       $desk_info = $mysql->getRow($sql);
       if($desk_info["left_rand_str"] && $desk_info["right_rand_str"]){
           return 1;
       }else{
           return 0;
       }
   }

   //剔除到某个用户
   public static function kickUser($uid)
   {
       $mysql = Event::get_mysql();
       $sql="update game_room set left_user_id = 0, left_rand_str = '', left_last_call = '', password = '', vipers='',is_all =0, one_called=0,called_num=0 where left_user_id = $uid";
       $mysql->query($sql);
       $sql="update game_room set right_user_id = 0,right_rand_str = '',right_last_call = '',vipers='', is_all =0,one_called=0,called_num=0 where right_user_id = $uid";
       $mysql->query($sql);
       
       $sql = "update game_room set one_called =0,called_num =0,init_gold = 0, gold = 0, is_all =0, vipers = '', call_first = 1 where left_user_id =0 and right_user_id =0 ";
       $mysql->query($sql);
       
        //删除观战模式的某个用户
       $sql = "select * from game_room where vipers like '%$uid%'";
       $result = $mysql->getRow($sql);
       if($result){
           $vipers = $result["vipers"];
           if($vipers == $uid){
               $sql = "update game_room set vipers = '' where id = '{$result[id]}'";
               $mysql->query($sql);
           }else{
               $vip_arr = explode(",", $vipers);
               $vip_ers = array();
               foreach($vip_arr as $key=>$val){
                   if($val == $uid){
                       continue;
                   }
                   $vip_ers[]=$val;
               }
               $vip_str = implode(",", $vip_ers);
               $sql = "update game_room set vipers = '$vip_str' where id = '{$result[id]}'";
               $mysql->query($sql);
           }
       }
   }

    //玩家赢了或者输了，操作member数据库记录起来
   public static function  gameOverCal($uid,$vectory,$gold)
   {
       $mysql = Event::get_mysql();
       $real_gold = 0;
       if($vectory>0){
            $sql = "update think_member set game_win = game_win + 1, game_win_wins = game_win_wins + 1 where id = $uid";
            $mysql->query($sql);
            Event::addUserGold($uid, $gold);
            //判断连赢了多少局
            $sql = "select game_win_wins from think_member where id = $uid";
            $wins = $mysql->getOne($sql);
            if($wins == 4 || $wins == 8){
                 GateWay::sendToUid($uid,JsonProtocol::encode(array("action"=>"game_win_wins","number"=>$wins)));
            }
            if($wins>=5){
                $sql = "select * from think_member_medal where uid = $uid and mid = 4";
                $medal = $mysql->getRow($sql);
                if(!$medal){
                    $data = array("uid"=>$uid,"mid"=>4,"add_time"=>date("Y-m-d H:i:s",time()));
                    $mysql->autoExecute("think_member_medal",$data);
                }
            }
       }else{
           $sql = "update think_member set game_lose = game_lose + 1, game_win_wins = 0 where id = $uid";
           $mysql->query($sql);
           $real_gold = Event::addUserGold($uid, (-1)*$gold);
       }
       return abs($real_gold);
   }
   
   //给玩家增加或者减少金币
   public static function  addUserGold($uid,$gold)
   {
       $mysql = Event::get_mysql();
       if($gold <0){
           $u_gold = $mysql->getOne("select gold from think_member where id = $uid");
           if($u_gold+$gold <0){
               $mysql->query("update think_member set gold = 0 where id = $uid");
               return $u_gold;
           }
       }
       $sql = "update think_member set gold = gold + $gold where id = $uid";
       $mysql->query($sql);
       return $gold;
   }

   //某个桌子开骰,判断输赢
   public static  function game_end_dec($game_id, $section_id, $desk_id, $seat, $uid,$last_call)
   {
       $mysql = Event::get_mysql();
       $sql = "select left_rand_str, right_rand_str, one_called from game_room where game_id = '$game_id' and section_id = '$section_id' and desk_id = '$desk_id'";
       $row = $mysql->getRow($sql);
       $arr = explode(",", $last_call);
       $left_rand = $row["left_rand_str"];
       $right_rand = $row["right_rand_str"];
       $one_called = $row["one_called"];
       if($seat == 1){
           $my_rand_str = $left_rand;
           $other_rand_str = $right_rand;
       }else{
           $my_rand_str = $right_rand;
           $other_rand_str = $left_rand;
       }
       $left_arr = explode(",", $left_rand);
       $right_arr = explode(",", $right_rand);
       $sum = array(0,0,0,0,0,0);
       for($i=0;$i<5;$i++){
           $left_s = $left_arr[$i];
           $sum[$left_s-1]= $sum[$left_s-1] +1;
           $right_s = $right_arr[$i];
           $sum[$right_s-1]=$sum[$right_s-1] +1;
       }
       if($one_called ==0 && $arr[1] != 1){
           $sum[$arr[1]-1] = $sum[$arr[1]-1] + $sum[0];
       }
       echo $sum[0].":".$arr[0];
       if($sum[$arr[1]-1]<$arr[0]){
           return array("vectory"=>1,"my_rand_str"=>$my_rand_str, "other_rand_str"=>$other_rand_str);//赢了
       }else{
           return array("vectory"=>0,"my_rand_str"=>$my_rand_str, "other_rand_str"=>$other_rand_str);//赢了
       }
    }

    //保存最近一次叫骰
    public static function save_call($game_id,$section_id, $desk_id, $seat,$uid, $call)
   {
       $mysql = Event::get_mysql();
       $call_arr = explode(",", $call);
       if($call_arr[1] == 1){
           $sql = "update game_room set one_called = 1 where game_id = '$game_id' and section_id = '$section_id' and desk_id = '$desk_id'";
           $mysql->query($sql);
       }
        $sql = "update game_room set called_num = called_num + 1 where game_id = '$game_id' and section_id = '$section_id' and desk_id = '$desk_id'";
        $mysql->query($sql);
        
       if($seat == 1){
           $sql="update game_room set left_last_call = '$call'  where game_id = '$game_id' and section_id = '$section_id' and desk_id = '$desk_id' and left_user_id = '$uid'";
           $mysql->query($sql);
           $sql = "select * from game_room where game_id = '$game_id' and section_id = '$section_id' and desk_id = '$desk_id'";
           $result = $mysql->getRow($sql);
           if($result["vipers"]){
               $vipers = explode(",", $result["vipers"]);
               if(is_array($vipers)){
                   foreach($vipers as $key=>$val){
                         $response= array("action"=>"game_vip_left_call", "call"=>$call);
                         GateWay::sendToUid($val, JsonProtocol::encode($response));
                   }
               }else{
                   $response= array("action"=>"game_vip_left_call", "call"=>$call);
                   GateWay::sendToUid($vipers, JsonProtocol::encode($response));
               }
           }
       }else{
            $sql="update game_room set right_last_call = '$call'  where game_id = '$game_id' and section_id = '$section_id' and desk_id = '$desk_id' and right_user_id = '$uid'";
            $mysql->query($sql);
            $sql = "select * from game_room where game_id = '$game_id' and section_id = '$section_id' and desk_id = '$desk_id'";
           $result = $mysql->getRow($sql);
            if($result["vipers"]){
               $vipers = explode(",", $result["vipers"]);
               if(is_array($vipers)){
                   foreach($vipers as $key=>$val){
                         $response= array("action"=>"game_vip_right_call", "call"=>$call);
                         GateWay::sendToUid($val, JsonProtocol::encode($response));
                   }
               }else{
                   $response= array("action"=>"game_vip_right_call", "call"=>$call);
                   GateWay::sendToUid($vipers, JsonProtocol::encode($response));
               }
           }
       }
       
   }
   
   public static function  get_call_first($game_id,$section_id, $desk_id){
       $mysql = Event::get_mysql();
       $sql = "select call_first from game_room where game_id = '$game_id' and section_id = '$section_id' and desk_id = '$desk_id'";
       $call_first = $mysql->getOne($sql);
       return $call_first;
   }

   //保存骰子的初始化数字
   public static function save_rand($game_id,$section_id, $desk_id, $seat,$uid, $rand_str,$gold)
   {
       $mysql = Event::get_mysql();
       if($seat == 1){
           $sql="update game_room set left_rand_str = '$rand_str',one_called=0  where game_id = '$game_id' and section_id = '$section_id' and desk_id = '$desk_id' and left_user_id = '$uid' ";
           $mysql->query($sql);
           $sql = "select * from game_room where game_id = '$game_id' and section_id = '$section_id' and desk_id = '$desk_id'";
           $result = $mysql->getRow($sql);
           if($result["vipers"]){
               $vipers = explode(",", $result["vipers"]);
               if(is_array($vipers)){
                   foreach($vipers as $key=>$val){
                         $response= array("action"=>"game_vip_left_str", "data_str"=>$rand_str);
                         GateWay::sendToUid($val, JsonProtocol::encode($response));
                   }
               }else{
                   $response= array("action"=>"game_vip_left_str", "data_str"=>$rand_str);
                   GateWay::sendToUid($vipers, JsonProtocol::encode($response));
               }
           }
       }else{
            $sql="update game_room set right_rand_str = '$rand_str'  where game_id = '$game_id' and section_id = '$section_id' and desk_id = '$desk_id' and right_user_id = '$uid'";
            $mysql->query($sql);
            $sql = "select * from game_room where game_id = '$game_id' and section_id = '$section_id' and desk_id = '$desk_id'";
            $result = $mysql->getRow($sql);
            if($result["vipers"]){
               $vipers = explode(",", $result["vipers"]);
               if(is_array($vipers)){
                   foreach($vipers as $key=>$val){
                         $response= array("action"=>"game_vip_right_str", "data_str"=>$rand_str);
                         GateWay::sendToUid($val, JsonProtocol::encode($response));
                   }
               }else{
                   $response= array("action"=>"game_vip_right_str", "data_str"=>$rand_str);
                   GateWay::sendToUid($vipers, JsonProtocol::encode($response));
               }
           }
       }
       
   }

   //获取自己对面桌子的玩家ID
   public static function get_other_user_id($game_id, $section_id, $desk_id,$seat)
   {
       $mysql = Event::get_mysql();
       
       if($seat == 1){
            $sql="select right_user_id from game_room where game_id = '$game_id' and section_id = '$section_id' and desk_id = '$desk_id'";
       }else{
            $sql="select left_user_id from game_room where game_id = '$game_id' and section_id = '$section_id' and desk_id = '$desk_id'";
       }
       $user_id = $mysql->getOne($sql);
       return $user_id;
   }

   //获取随机数
   public  static function get_random()
   {
       $arr = array();
       for($i=0;$i<5;$i++)
       {
           $arr[]=  rand(1, 6);
       }
       
       $sum = array(0,0,0,0,0,0);
       for($i=0;$i<5;$i++){
           $sum[$arr[$i]-1]++;
       }
       $one_num = 0;
       $five_num = 0;
       for($j=0;$j<6;$j++){
           if($sum[$j] == 1){
               $one_num ++;
           }
           if($sum[$j] == 5){
               $five_num ++;
           }
       }
       if($one_num == 5 || $five_num == 1){
           return Event::get_random();
       }else{
           return implode(",", $arr);
       }
   }

   //搜索某个桌子
   public static function get_search_desk($message){
       $section_id = $message["section_id"];
       $game_id = $message["game_id"];
       $desk_id = $message["desk_id"];
       $mysql = Event::get_mysql();
       $sql="select * from game_room where game_id = '$game_id' and section_id = '$section_id' and desk_id = '$desk_id'";
       $desks = $mysql->getAll($sql);
       return $desks;
   }

   //获取某个分区所有桌子的情况
   public static function get_all_desks($message){
       $section_id = $message["section_id"];
       $game_id = $message["game_id"];
       $mysql = Event::get_mysql();
       $filter = isset($message["filter"])?$message["filter"]:0;
       if(!$filter){
           $orderby = "desk_id";
       }elseif($filter == 1){
           $orderby = "is_all";
       }else{
           $orderby = "create_time desc";
       }
       $sql="select * from game_room where game_id = '$game_id' and section_id = '$section_id' and (left_user_id !=0 or right_user_id !=0) order by $orderby";
       $desks = $mysql->getAll($sql);
       if($desks){
           echo "1";
           foreach ($desks as $key=>$val){
               $left_user_id = $val["left_user_id"];
               $right_user_id = $val["right_user_id"];
               if($left_user_id){
                   echo "2";
                   $sql = "select * from think_member where id = '$left_user_id'";
                   $left_info = $mysql->getRow($sql);
                   $pic = $left_info["pic"];
                   if($pic && strstr($pic,"http://") === FALSE){
                        $pic = "http://218.244.158.213/smeoa/Data/Files/".$pic;
                        $left_info["pic"] = $pic;
                   }
                   $left_user_info= array();
                   $left_user_info["pic"] = $left_info["pic"];
                   $left_user_info["nickname"] = $left_info["nickname"];
                   $left_user_info["gold"] = $left_info["gold"];
                   $left_user_info["game_win"] = $left_info["game_win"];
                   $left_user_info["game_lose"] = $left_info["game_lose"];
                   $val["left_user_info"] = $left_user_info;
               }
               if($right_user_id){
                   echo "3";
                   $sql = "select * from think_member where id = '$right_user_id'";
                   $right_info = $mysql->getRow($sql);
                   $pic = $right_info["pic"];
                   if($pic && strstr($pic,"http://") === FALSE){
                        $pic = "http://218.244.158.213/smeoa/Data/Files/".$pic;
                        $right_info["pic"] = $pic;
                   }
                   $right_user_info= array();
                   $right_user_info["pic"] = $right_info["pic"];
                   $right_user_info["nickname"] = $right_info["nickname"];
                   $right_user_info["gold"] = $right_info["gold"];
                   $right_user_info["game_win"] = $right_info["game_win"];
                   $right_user_info["game_lose"] = $right_info["game_lose"];
                   $val["right_user_info"] = $right_user_info;
               }
               $desks[$key]=$val;
           }
       }
       return $desks;
   }
   
   //设置桌子密码
   public static function  set_desk_password($uid, $message){
       $game_id = $message["game_id"];
       $section_id = $message["section_id"];
       $desk_id = $message["desk_id"];
       $password = $message["password"];
       $mysql = Event::get_mysql();
       $sql = "update game_room set `password` = '$password' where game_id = '$game_id' and section_id = '$section_id' and desk_id = '$desk_id'";
       $succ = $mysql->query($sql);
       return $succ;
   }

   //把某个玩家加到某个桌子
   public static function add_to_desk($uid,$message){
       $game_id = $message["game_id"];
       $section_id = $message["section_id"];
       $desk_id = $message["desk_id"];
       $mysql = Event::get_mysql();
       $is_new = 0;
       if($desk_id == 0){
            $sql = "select desk_id from game_room where game_id = $game_id and section_id = $section_id and left_user_id = 0 and right_user_id = 0 order by desk_id ";
            $result = $mysql->getOne($sql);
            $desk_id = $result;
            $is_new = 1;
       }
       $sql = "select * from game_room where game_id = $game_id and section_id = $section_id and desk_id = $desk_id";
       $result = $mysql->getRow($sql);
       if($result["left_user_id"] && $result["right_user_id"]){
           $vipers = $result["vipers"];
           if($vipers){
               $vipers = $vipers.",".$uid;
           }else{
               $vipers = $uid;
           }
           $sql = "update game_room set vipers = '$vipers' where id = '{$result['id']}'";
           $mysql->query($sql);
           return array(0,0,$desk_id,$is_new,0,"",$result);
       }else{
           if(!$result["left_user_id"]){
               $result["left_user_id"]=$uid;
               $time = time();
               $sql = "update game_room set left_user_id = $uid, create_time = $time where game_id = $game_id and section_id = $section_id and desk_id = $desk_id";
               $mysql->query($sql);
               //右边有人有残留
               if($result["right_user_id"]){
                    //给右边的那个人发消息通知左边边的人已经来了
                    $response = array("action"=>"add_desk_other","come_uid"=>$uid,"game_id"=>$game_id,"desk_id"=>$desk_id,"section_id"=>$section_id);
                    GateWay::sendToUid($result["right_user_id"], JsonProtocol::encode($response));
                    //更新一下由哪个玩家来开始
                    $mysql->query("update game_room set call_first = 2,is_all = 1 where game_id = $game_id and section_id = $section_id and desk_id = $desk_id");
               }
               return array(1,$result["right_user_id"],$desk_id,$is_new,0,"",$result["gold"]);
           }else{
               if(!$result["password"]){
                    //给左边的那个人发消息通知右边的人已经来了
                    //左边的是机器人
                    if(array_search($result["left_user_id"], Event::$robot_ids)===FALSE){
                        $response = array("action"=>"add_desk_other","come_uid"=>$uid,"game_id"=>$game_id,"desk_id"=>$desk_id,"section_id"=>$section_id);
                        //sleep(3000);
                        for($i=0;$i<60000000;$i++){
                            ;
                        }
                        GateWay::sendToUid($result["left_user_id"], JsonProtocol::encode($response));
                    }else{
                        //机器人初始化的工作
                        
                    }
                    $response = array("action"=>"add_desk_other","come_uid"=>$uid,"game_id"=>$game_id,"desk_id"=>$desk_id,"section_id"=>$section_id);
                    GateWay::sendToUid($result["left_user_id"], JsonProtocol::encode($response));
                    $result["right_user_id"]=$uid;
                    $sql = "update game_room set right_user_id = $uid, is_all =1 where game_id = $game_id and section_id = $section_id and desk_id = $desk_id";
                    $mysql->query($sql);
                    return array(2,$result["left_user_id"],$desk_id,$is_new,0,"",$result["gold"]);
               }else{
                   return array(2,$result["left_user_id"],$desk_id,$is_new,1,$result["password"],$result["gold"]);
               }
               
           }
       }
   }

   
   /**
    * 当用户断开连接时触发的方法
    * @param string $address 和该用户gateway通信的地址
    * @param integer $uid 断开连接的用户id 
    * @return void
    */
   public static function onClose($uid)
   {
       // [这步是必须的]删除这个用户的gateway通信地址
       GateWay::deleteUidAddress($uid);
       
       // 广播 xxx 退出了
       //GateWay::sendToAll(JsonProtocol::encode(array('from_uid'=>'SYSTEM', 'message'=>"$uid logout\n", 'to_uid'=>'all')));
       $sql = "select * from game_room where left_user_id = '$uid' or right_user_id = '$uid'";
       $mysql = Event::get_mysql();
       $message_data = $mysql->getRow($sql);
       
       //清空该用户所占用的桌子位置
       Event::kickUser($uid);
       
       if($message_data){
            $desks = Event::get_all_desks($message_data);
            $response = array("action"=>"get_all_desks","lists"=>$desks);
            GateWay::sendToAll(JsonProtocol::encode($response));
       }
   }
   
   /**
    * 用户第一次链接时，根据用户传递的消息（一般是用户名 密码）返回当前uid
    * 这里只是返回了时间戳相关的一个数字
    * @param string $message
    * @return number
    */
   protected static function checkUser($message)
   {
       return substr(strval(microtime(true)), 3, 10)*100;
   }
}
